<template>
  <PrivacyPopup v-if="privacyShow" ref="privacyGroupPlugin" :auto-judge="privacyShow"></PrivacyPopup>
  <view class="home-view" :class="{ 'connect-required': connectRequired }">
    <PageLayout full safe-area="none">
      <template #header>
        <HeaderLayout safe-capsule :header-style="headerStyle">
          <template #left>
            <image
              class="page-logo"
              mode="aspectFit"
              :src="connectRequired ? '/static/LogoLight.png' : '/static/LogoDark.png'"
            ></image>
          </template>
          <template #right>
            <TrackButton track-id="Navigator.Home.MessageCenter.Icon">
              <view class="message-button" hover-class="hovering" @click="jumpToMessageList">
                <image class="message-icon" :src="messageIcon" mode="aspectFit" />
                <view class="unread-dot" v-if="showUnReadView && authStore.isLogin"></view>
              </view>
            </TrackButton>
          </template>
        </HeaderLayout>
      </template>

      <view class="page-body">
        <!-- 虚拟体验入口 -->
        <view class="virtual-entry">
          <view class="virtual-button" @click="isVirtual ? exitVirtualExperience() : toVirtualExperience()">
            <block v-if="isVirtual">
              <view class="virtual-text">{{ $t('Navigator.Home.VirtualExperience.Exit.Text') }}</view>
              <image class="virtual-icon" mode="aspectFit" src="/static/home/VirtualExperienceExit.png" />
            </block>
            <block v-else>
              <view class="virtual-text">{{ $t('Navigator.Home.VirtualExperience.Text') }}</view>
              <image
                class="virtual-icon"
                mode="aspectFit"
                :src="
                  connectRequired ? '/static/home/VirtualExperienceLight.png' : '/static/home/VirtualExperienceDark.png'
                "
              />
            </block>
          </view>
        </view>

        <!-- 连接家电 -->
        <view class="connect-view" v-show="connectRequired">
          <view class="connect-title">
            <text>{{ $t('Navigator.Home.ConnectYou.Text') }}</text>
            <text>{{ $t('Navigator.Home.FirstAppliance.Text') }}</text>
          </view>
          <view class="connect-intro">
            <image class="connect-image" mode="widthFix" :src="`${netconfig.ASSETSPRE_ICONS}Appliance_3.0_Home.png`" />
            <view class="connect-action">
              <TrackButton track-id="Navigator.Home.ClickAddAppliance.Text">
                <ActionButton @click="addAppliance">
                  <text>+ {{ $t('Navigator.Home.ClickAddAppliance.Text') }}</text>
                </ActionButton>
              </TrackButton>
            </view>
          </view>
        </view>

        <!-- 我的家电 -->
        <view class="my-appliances" v-show="!connectRequired">
          <!-- 骨架屏 -->
          <template v-if="loading && applianceStore.list.length === 0 && !isVirtual">
            <view class="skeleton-item header-skeleton"></view>
            <view class="skeleton-grid appliance-list-skeleton">
              <view v-for="count in 6" :key="count" class="skeleton-item appliance-card-skeleton"></view>
            </view>
          </template>
          <!-- 家电列表 加载完成 -->
          <template v-else>
            <view class="my-appliances-header">
              <view class="my-appliances-title">{{
                isVirtual ? $t('Navigator.Home.VirtualExperience.Title') : $t('Navigator.Home.MyAppliance.Title')
              }}</view>
            </view>

            <ApplianceCards
              :list="applianceList"
              :show-add-appliance="!isVirtual"
              @select="onSelectAppliance"
              @add="addAppliance"
            />
          </template>
        </view>
        <!-- <ErrorTips v-model:visible="errorTipsFlag" :error-text="errorTipsText"></ErrorTips> -->
      </view>
      <Modal
        :visible="showShare"
        :title="$t('APP.Common.Tips.Text')"
        :cancel-text="$t('APP.Common.Cancel.Text')"
        :ok-text="$t('APP.Common.Confirm.Text')"
        @cancel="cancelShare"
        @ok="confirmShare"
      >
        <view class="share-text">{{ shareMessage }}</view>
      </Modal>

      <Modal :visible="showSettingError" :title="$t('APP.Common.BoolthTips.Text')" @ok="openSettings" ok-text="去打开">
        <view class="model-tips system-modal">
          {{ $t('APP.Common.BoolthTips.TitleTips.Text') }}
        </view>
        <image :src="showSettingPic" style="width: 100%" mode="aspectFit"></image>
      </Modal>
      <Modal
        :visible="showLocationErrorPic ? true : false"
        :title="$t('APP.Pairing.Error.Android.WXMPLocation.Text')"
        @ok="showLocationErrorPic = ''"
        ok-text="知道了"
      >
        <image :src="showLocationErrorPic" style="width: 100%" mode="aspectFit"></image>
      </Modal>
      <ActivityPopup v-model:visible="activityPopupVisible" :appliance="applianceList" ref="activityPopupRef" />
    </PageLayout>
  </view>
</template>
<script lang="ts">
export type ShareOptionsType = {
  sharingtoken?: string
  name?: string
  type?: string
}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import ApplianceCards from '../components/applianceCards.vue'
import loginHelper from '@/pluginHelper/login'
import Modal from '@/common/modal.vue'

import { useColorTransition } from '@/utils/composition/useHeaderTransition'
import { useApplianceStore } from '@/store/appliance'
import { getUserIsHaveMessageRemind, type UserIsHaveMessageRemindType } from '@/api/wxuserSignInfo'
import { declineShare, acceptShare } from '@/api/wxuserSignInfo'

import { useAuthStore } from '@/store/auth'
import type { ErrorResponse } from '@/utils/request'
import { actionDebounce, getPageQuery, toPage, checkReason } from '@/utils/mpHelper'
import TrackButton from '@/dataReport/components/TrackButton.vue'
import { useErrors, type ErrorType } from '@/handle/errors'
import { CacheTypes, useCache } from '@/controller/base/cacheHelper'
import type { ApplianceData } from '@/types/appliance'
import { useI18n } from 'vue-i18n'
import ActionButton from '@/common/actionButton/actionButton.vue'
import ActivityPopup from '../components/activityPopup.vue'
import {
  useApplianceListMessageListener,
  useApplianceMethods,
  toOtherMPCheckUp,
} from '../components/useApplianceMethods'
import netconfig from '@/config/netconfig'
import { useGlobalStore } from '@/store/global'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import { loadFileModule } from '@/controller/demo/utils'
import { orderPermanentInfo } from '@/utils/deviceMessageSubscribe/deviceMessage'
import { toTargetMiniProgramTypes } from '@/constants/AppInfo'
import {
  checkLocationPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from '@/utils/basicHelper'
import { useEnvStore } from '@/store/env'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { resetPermanentInfo } from '@/api/deviceMessageSubscribe'
import { httpRequestErrorHandle } from '@/httpRequest/helper/errorHelper'
import PrivacyPopup from '../components/privacyPopup.vue'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { PairingConfirmAgreePrivacy } from '@/constants/UniEventKeys'
import { useUniEvent } from '@/utils/mpHelper'
import type { ApplianceType } from '@/api/content'

const privacyGroupPlugin = ref<InstanceType<typeof PrivacyPopup> | null>(null)

const envStore = useEnvStore()
const plantFrom = computed(() => envStore.systemInfo.platform)

const globalStore = useGlobalStore()
const showVersonError = ref(false)
const showPairError = ref(false)
const showSettingError = ref(false)
let timeoutTimer: number
const props = defineProps<{
  isActive: boolean
  virtual: boolean
  fromOtherPage?: boolean
}>()
const emit = defineEmits<{
  (e: 'update:virtual', isVirtual: boolean): void
}>()

const isVirtual = computed({
  get() {
    return props.virtual
  },
  set(virtual) {
    emit('update:virtual', virtual)
  },
})

const i18n = useI18n()
const authStore = useAuthStore()
const applianceStore = useApplianceStore()
const { transitionRef } = useColorTransition({
  boundaryHeight: 50,
  colorVector: [220, 220, 220],
})
const headerStyle = computed(() => ({
  color: '#333',
  ...transitionRef.value,
}))

let selectFlag = false
const privacyShow = ref(true)

useUniEvent(PairingConfirmAgreePrivacy, () => {
  privacyShow.value = false
})

/**
 * Tab组件生命周期
 */
defineExpose({
  onPageLoad,
  onActive,
})
onLoad((option: any) => {
  checkPrivacy()
})
/**
 * 检测微信的隐私权限
 */
function checkPrivacy() {
  if (!authStore.isLogin) {
    return
  }
}

onShow(() => {
  selectFlag = false
  privacyGroupPlugin.value?.addPrivacyApiEventMonitor()
})

function openSettings() {
  showSettingError.value = false
  showLocationErrorPic.value = ''
  uni.openSetting({
    success: (res) => {},
  })
}
function onPageLoad(query?: Record<string, any>) {
  // 分享弹框
  let shareOptions = getPageQuery()
  judgeSharePop(shareOptions)

  if (!authStore.isLogin) {
    if (props.fromOtherPage) return
    // setTimeout(() => {
    //   const pages = getCurrentPages()
    //   const currentPage = pages[pages.length - 1]
    //   loginHelper.noCiamIdLogin(undefined, {
    //     path: currentPage.route,
    //     query: getPageQuery(),
    //   })
    // }, 1000)
    return
  }

  // 判断用户是否重新加载小程序
  let isNewUser = uni.getStorageSync('isNewUser')
  if (!isNewUser) {
    resetPermanentInfo()
    uni.setStorageSync('isNewUser', true)
  }

  if (query?.isVirtual) {
    isVirtual.value = query?.isVirtual === 'true'
  }
  if (query?.addAppliance === 'true') {
    addAppliance()
  }
}
function onActive() {
  loadData().then(() => {
    // WebsocketManager.instance.connectWebsocket()
  })
  if (!authStore.isLogin) {
    nextTick(() => {
      activityPopupRef.value?.loadData()
    })
  }
}

/**
 * 页面状态
 */
const loading = ref(false)
watchEffect(() => {
  if (!props.isActive) {
    return setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
  }

  // 连接视图 状态栏文字全白 否则全黑
  const showLightNavigationBar = connectRequired.value
  return setNavigationBarColor({
    frontColor: showLightNavigationBar ? '#ffffff' : '#000000',
    backgroundColor: '#ffffff',
  })
})

function setNavigationBarColor(options: UniNamespace.SetNavigationbarColorOptions) {
  try {
    uni.setNavigationBarColor(options)
  } catch (e) {}
}

// 监听WebSocket
useApplianceListMessageListener()

// 加载数据
async function loadData() {
  if (!authStore.isLogin) return

  loadUserMessageInfo()

  loading.value = true
  applianceStore
    .loadList(true)
    .then(() => {
      updatePosterPage()
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 添加缓存: 程序列表
 */
useCache<ApplianceData[]>({
  type: CacheTypes.ApplianceList,
  watchTrigger: () => applianceStore.list,
  setCacheTransformer(data) {
    return data.map((appliance) => ({
      ...appliance,
      // 维持connected的值 用于从缓存进入页面时 判断是否可以提前调程序等接口
      // connected: false,
      stateType: null,
    }))
  },
  onCacheLoad(list) {
    if (Array.isArray(list)) {
      applianceStore.list = list
    }
  },
})

/**
 * 家电方法
 */
const applianceMethods = useApplianceMethods()

// 家电列表
const demoApplianceList = ref<ApplianceData[]>([])
const applianceList = computed(() => (isVirtual.value ? demoApplianceList.value : applianceStore.list))
// 加载虚拟家电列表
async function loadVirtualList() {
  const mod = await loadFileModule<{ default: ApplianceData[] }>('/demo/list')
  demoApplianceList.value = mod.default
}
loadVirtualList()

// 家电方法
async function onSelectAppliance(appliance: ApplianceData) {
  // 因为微信的限制不能加防抖防重复点击类似的方法，settimeout也有问题 仍然会偶现问题
  // 虚拟家电不进行数据请求
  if (selectFlag) return
  selectFlag = true
  if (isVirtual.value) {
    globalStore.is_virtual = true
    selectFlag = false
    return toPage(`/pages/appliance/Demo/${appliance.type}/${appliance.type}`)
  }
  const isOtherMPTypes = toTargetMiniProgramTypes.includes(appliance.type)

  if (isOtherMPTypes) {
    toOtherMPCheckUp(appliance)
    selectFlag = false
  } else {
    // 设备消息订阅
    let res: any = null
    try {
      res = await orderPermanentInfo(appliance.haId)
    } catch (error) {
      res = error
    } finally {
      selectFlag = false
      // 设备被移除或者移除分享场景
      if (res && res.code == 20012) {
        return
      } else {
        return applianceMethods.chooseHA(appliance)
      }
    }
  }
}

/**
 * 热门活动
 */
const activityPopupVisible = ref(false)
const activityPopupRef = ref<InstanceType<typeof ActivityPopup> | null>(null)

/**
 * 获取用户信息和未读信息
 */
const showUnReadView = ref(false)
const messageIcon = computed(() =>
  connectRequired.value ? '/static/home/MessageLight.png' : '/static/home/MessageDark.png'
)
async function loadUserMessageInfo() {
  const res = await getUserIsHaveMessageRemind()
  showUnReadView.value = (res.data as UserIsHaveMessageRemindType).unread
}
/**
 * 更新海报
 */
function updatePosterPage() {
  if (!isVirtual.value) {
    nextTick(() => {
      let appliances: ApplianceType[] = []
      applianceList.value.forEach((items) => {
        appliances.push({
          brand: items.brand,
          type: items.type,
        })
      })
      activityPopupRef.value?.loadData(appliances)
    })
  }
}
/**
 * 虚拟体验
 */
function toVirtualExperience() {
  isVirtual.value = true
  safeTrack(() => {
    trackEvent('Navigator.Home.VirtualExperience.Text', {}, TrackType.BusinesssScene)
  })
}
function exitVirtualExperience() {
  isVirtual.value = false
  globalStore.is_virtual = false
  safeTrack(() => {
    trackEvent('Navigator.Home.VirtualExperience.Exit.Text', {}, TrackType.BusinesssScene)
  })
}

/**
 * 跳转消息中心页面
 */
const messageCenterPath = 'pages/messagecenter/messagecenter'
const jumpToMessageList = actionDebounce({
  delay: 1500,
  call: async () => {
    if (!authStore.isLogin) {
      loginHelper.noCiamIdLogin(undefined, { path: messageCenterPath })
      return
    }
    await toPage(`/${messageCenterPath}`)
  },
})

/**
 * 添加家电
 */
const connectRequired = computed(() => {
  // 加载中且无家电 优先显示骨架屏
  if (loading.value && !applianceStore.list.length) return false
  // 虚拟体验 优先显示
  if (isVirtual.value) return false

  // 未登录 或 无家电
  return !authStore.isLogin || !applianceStore.list.length
})
const pairingPath = 'pages/pairing/chooseMode/index'
// 微信版本号弹窗提示文本
const showPairErrorText = ref('')
const showLocationErrorPic = ref<string>('')
// 用户操作提示图
const showSettingPic = ref<string | boolean>('')
const addAppliance = actionDebounce({
  delay: 2000,
  call: async () => {
    const checkSetting = await checkReason()

    if (!checkSetting) {
      return
    } else if (checkSetting != true && checkSetting.indexOf('.jpg')) {
      showSettingPic.value = checkSetting
      return (showSettingError.value = true)
    }
    // 位置判断
    try {
      await checkLocationPermission()
    } catch (error: any) {
      if (!error.Location) return
      if (error.Location === OS_SYSTEM_LOCATION_PERMISSION) {
        if (plantFrom.value === 'ios') {
          return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS2.png`) //蓝牙使用判断
        } else {
          return uni.showModal({
            title: i18n.t('LocationPermission.System.Dialog.Title.Text'),
            content: i18n.t('LocationPermission.System.Pairing.Dialog.Text'),
          })
        }
      } else if (error.Location === APPLICATION_LOCATION_PERMISSION) {
        if (plantFrom.value === 'ios') {
          return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS.png`) //蓝牙使用判断
        } else {
          return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_Android.png`) //蓝牙使用判断
        }
      } else if (error.Location === WXMP_LOCATION_PERMISSION) {
        return uni.showModal({
          title: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.title.text'),
          content: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.text'),
          confirmText: i18n.t('APP.Common.GoToAuthorization.Text'),
          success: (res) => {
            if (res.confirm) {
              openSettings()
            } else if (res.cancel) {
              console.log('cancel...')
            }
          },
        })
      }
    }
    if (!authStore.isLogin) {
      loginHelper.noCiamIdLogin(undefined, { path: pairingPath })
      return
    }
    await applianceMethods.addAppliance()
  },
})

/**
 * 分享弹框
 */
let confirmSharing = false
const sharename = ref('')
const sharetype = ref('')
const sharetoken = ref('')
const showShare = ref(false)
const shareMessage = computed(() => i18n.t('ShareAppliance.ConfirmAccept.Title').replace('{userName}', sharename.value))
const { errorTipsFlag, errorTipsText, handleCommonShareError } = useErrors()
//判断是否弹分享弹框
function judgeSharePop(options: ShareOptionsType) {
  if (options.sharingtoken) {
    sharetoken.value = options?.sharingtoken as string
    sharename.value = decodeURIComponent(options?.name as string)
    sharetype.value = options?.type as string
    showShare.value = true
  }
}
//取消分享
async function cancelShare() {
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin()
    return
  }
  confirmSharing = true
  const res = await declineShare(sharetoken.value)
  if (res.code === 0) {
    showShare.value = false
  } else {
    if (res.code !== 10001) {
      showShare.value = false
    }
    httpRequestErrorHandle(res as unknown as ErrorResponse)
  }
}
//确定分享
async function confirmShare() {
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin()
    return
  }
  if (confirmSharing) return
  const res = await acceptShare(sharetoken.value, sharetype.value)
  if (res.code === 0) {
    showShare.value = false
  } else {
    if (res.code !== 10001) {
      showShare.value = false
    }
    httpRequestErrorHandle(res as unknown as ErrorResponse)
  }

  if (authStore.isLogin) {
    confirmSharing = true
    applianceStore.loadList(true)
  }
}
</script>

<style lang="less">
@import '@/styles/skeleton.less';

@horizontalGap: 32rpx;
@verticalGap: 24rpx;

.home-view,
.page-body {
  height: 100%;
}

.home-view {
  background: linear-gradient(180deg, rgba(45, 55, 70, 0.2) 0%, rgba(255, 255, 255, 0.2) 52.61%), #ffffff;
  color: var(--dark-color);

  &.connect-required {
    background: linear-gradient(180deg, var(--dark-color) 0%, #ffffff 58.59%), #ffffff;
    color: #ffffff;
    .virtual-entry {
      top: 54rpx;
    }
  }
}

.page-body {
  position: relative;
}

// 导航栏样式
.page-logo {
  width: 244rpx;
  height: 40rpx;
  margin-left: @horizontalGap;
}

.message-button {
  width: 40rpx;
  height: 40rpx;
  margin-right: 40rpx;
  position: relative;

  &.hovering {
    filter: brightness(0.8);
  }

  .message-icon {
    width: 100%;
    height: 100%;
  }

  .unread-dot {
    position: absolute;
    right: 0rpx;
    top: 0rpx;
    width: 8rpx;
    height: 8rpx;
    border-radius: 50%;
    background-color: #eb3a3a;
  }
}

// 虚拟体验
.virtual-entry {
  position: absolute;
  top: 40rpx;
  right: 32rpx;
}

.virtual-button {
  display: flex;
  align-items: center;

  .virtual-text {
    width: 50rpx;
    height: 56rpx;
    font-weight: 500;
    font-size: 24rpx;
    line-height: 28rpx;
    word-break: break-all;
  }

  .virtual-icon {
    width: 52rpx;
    height: 52rpx;
    margin-left: 10rpx;
  }
}

// 连接家电
.connect-view {
  width: 100%;
  padding-top: 40rpx;

  .connect-title {
    display: flex;
    flex-flow: column nowrap;
    margin: 0 @horizontalGap 60rpx;
    width: 360rpx;
    font-size: 64rpx;
    font-weight: 600;
    line-height: 80rpx;
    color: #ffffff;

    > text + text {
      margin-top: 8rpx;
    }
  }

  .connect-intro {
    width: 100%;
    height: 700rpx;
    position: relative;
    .connect-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
    }
    .connect-action {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      padding: 0 @horizontalGap;
      box-sizing: border-box;
    }
  }
}

// 热门活动
// .hot-active {
//   padding: 40rpx;

//   .hot-active-title {
//     display: flex;
//     justify-content: space-between;
//     align-items: center;
//     .hot-title {
//       color: #3c3c3c;
//       font-size: 32rpx;
//       font-weight: 500;
//     }

//     .hot-more {
//       font-size: 24rpx;
//     }
//   }

//   .hot-image {
//     width: 100%;
//     height: 160rpx;
//     background-color: #dcdcdc;
//     margin-top: 20rpx;
//   }
// }

// 我的家电
.my-appliances {
  padding: @verticalGap @horizontalGap;

  .my-appliances-header {
    margin-bottom: 40rpx;
  }

  .my-appliances-title {
    font-weight: 600;
    font-size: 64rpx;
    line-height: 90rpx;
    letter-spacing: 0.12px;
    color: var(--dark-color);
  }
}

/*
 * 骨架屏
 */
.header-skeleton {
  width: 264rpx;
  height: 90rpx;
}

.appliance-list-skeleton {
  margin: 32rpx 0;
  gap: 24rpx;
}

.appliance-card-skeleton {
  height: 232rpx;
}
</style>
